<?php

use think\facade\Db;

class TengxunAD
{
    # 微信小程序ID
    const wechat_app_id = "wxd42bd7cfb3bf5b40";

    # 密钥
    const access_token = "8d5dc1f66e3413232fb09c1ff023d8a8";

    # DataNexus账号id
    const account_id = 55994695;

    const user_action_set_id = 1216841203;

    const action_type_list = [
        '页面访问' => 'PAGE_VIEW',
        '下单' => 'COMPLETE_ORDER',
        '付费' => 'PURCHASE',
    ];


    /**
     * 用户行为添加/更新 https://developers.e.qq.com/v3.0/docs/api/user_actions/add
     * https://datanexus.qq.com/doc/develop/guider/interface/conversion/trackingcgi_api_miniprogram 
     * https://datanexus.qq.com/doc/develop/guider/interface/user_id#%E6%83%85%E5%86%B51%E8%90%BD%E5%9C%B0%E9%A1%B5-url-%E4%B8%8A%E8%8E%B7%E5%8F%96
     * @param string $wechat_openid 用户ID
     * @param string $action_type
     * @return void
     * @throws \Random\RandomException
     */
    public function add(string $wechat_openid,string $action_type,string $client_id = '',int $product_value = 0)
    {
        if (empty($client_id)) {
            return ;
        }
        // 判断action_type类型是否在列表中
        $action_type_key = array_keys(self::action_type_list);
        if (!in_array($action_type,$action_type_key)) {
            throw new Exception('action_type类型错误');
        }

        $timestamp = time();
        $nonce = bin2hex(random_bytes(16));
//        $url = "https://api.e.qq.com/v1.3/user_actions/add?access_token=".self::access_token."&timestamp={$timestamp}&nonce={$nonce}";
        $url = "https://api.e.qq.com/v3.0/user_actions/add?access_token=".self::access_token."&timestamp={$timestamp}&nonce={$nonce}";

        $payload = [
            'account_id'         => self::account_id,               // 示例账户ID
            'user_action_set_id' => self::user_action_set_id,               // DATANEXUS 数据源ID
            'actions'            =>[
                [
//                    'outer_action_id' => '示例唯一行为 id_请指定',  # 用户自定义的行为 id 标识，最大值 255 字节
                    'action_time'     => $timestamp,  # 行为发生时，客户端的时间点。UNIX 时间，单位为秒，如果不填将使用服务端时间填写，最大值 2147483647
                    'user_id'         => [
                        'wechat_openid' => $wechat_openid,
                        'wechat_app_id' =>  self::wechat_app_id
                    ],
                    'action_type'  => self::action_type_list[$action_type],
//                    'action_param' => [
//                        'value'      => 28,  # 订单价值，单位：分，100代表1元。体现转化带来的价值，一般在 action_type 为 COMPLETE_ORDER 或 PURCHASE 行为时选填
//                        'object'   => 'order',  # 行为对象，例如 action_type 为 VIEW_CONTENT 时，object=product代表“商品页面浏览
//                    ],
//                    'url' => '', # 网页应用填写，url，请填写效果数据发生 h5 页面 URL 地址，如datanexus.qq.com，最大值 2048 字节

//                    'channel' => 'TENCENT',
//                    'ext_info' => []
                ]
            ]

        ];

        if ($action_type == '下单' || $action_type == '付费') {
            if ($product_value  == 0){
                throw new Exception('product_value金额错误');
            }
            $payload['actions'][0]['action_param'] = [
                'value' =>  (int)bcmul($product_value,100,0),
                'object' => $action_type == '下单'?'order':'order_pay'
            ];
        }
        if ($client_id != ''){
            $payload['actions'][0]['trace'] = [
                'click_id' => $client_id
            ];
        }



        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL            => $url,
            CURLOPT_POST           => true,
            CURLOPT_HTTPHEADER     => ['Content-Type: application/json'],
            CURLOPT_POSTFIELDS     => json_encode($payload, JSON_UNESCAPED_UNICODE),
            CURLOPT_RETURNTRANSFER => true,
        ]);

        $response = curl_exec($ch);
        curl_close($ch);

        Db::table('jjjshop_datanexus')->insert([
            'params'=> json_encode($payload),
            'user_id' => '',
            'type' => $action_type,
            'value' => $product_value,
            'result' => $response === false ? 'Curl error: ' . curl_error($ch) : $response,
            'create_time' => time(),
        ]);

        if ($response === false) {
            echo 'Curl error: ' . curl_error($ch);
        } else {
            return $response;
        }
    }


    private function generatedActionsData(string $type,string $url,array $ext_info)
    {
        if (!in_array($type, ['user_id','click_id'])){
            throw new Exception('type错误');
        }
        

        //$ext_info
        //device_brand	string
        //设备品牌，长度最大 255 字节
        //model	string
        //设备机型，长度最大 255 字节
        //os_version	string
        //操作系统版本，长度最大 255 字节
        //ip	string
        //设备 ip，需上报行为发生时的 ip，长度最大 255 字节



    }


}